package com.tbm.console.proj.json;

import com.alibaba.fastjson.JSONArray;
import com.tbm.console.base.controller.BaseController;
import com.tbm.console.common.constant.InsUpdDelFlagConstant;
import com.tbm.console.proj.entity.SystemButton;
import com.tbm.console.proj.entity.SystemMenu;
import com.tbm.console.proj.entity.SystemRole;
import com.tbm.console.proj.entity.SystemUser;
import com.tbm.console.proj.service.SystemButtonService;
import com.tbm.console.proj.service.SystemMenuService;
import com.tbm.console.proj.service.SystemRoleService;
import com.tbm.console.util.PageData;
import com.tbm.console.util.RightsHelper;
import com.tbm.console.util.TreeMenuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Slf4j
public class SystemRoleJson extends BaseController {

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemButtonService systemButtonService;

    /**
     * 后台分页
     * @param start
     * @param length
     * @return
     */
    @RequestMapping("/role-list-json/{start}/{length}")
    public Map<String,Object> roleListJson(@PathVariable("start") Integer start, @PathVariable("length") Integer length){
        PageData pageData = new PageData();
        pageData.put("total", systemRoleService.count());
        pageData.put("rows", systemRoleService.findAll(start-1,length));
        return pageData;
    }

    /**
     * 分配权限
     * @param rights
     * @param id
     * @return
     */
    @RequestMapping("/role-assign/{rights}/{id}")
    public String roleInsUpd(@PathVariable("rights")Object rights,@PathVariable("id") Integer id){
        String newRights = "R"+RightsHelper.sumRights(rights.toString().split(",")).toString();
        PageData pageData = new PageData();
        pageData.put("id", id);
        List<SystemRole> allOrOne = systemRoleService.findAll(pageData);
        if(null!=allOrOne||0!=allOrOne.size()){
            allOrOne.get(0).setRights(newRights);
            systemRoleService.saveAll(allOrOne);
        }
        log.info("aa");
        return "";
    }



    /**
     * 分配权限
     * @param rights
     * @param id
     * @return
     */
    @RequestMapping("/button-assign/{rights}/{id}")
    public String buttonInsUpd(@PathVariable("rights")Object rights,@PathVariable("id") Integer id){
        String newRights = "B"+RightsHelper.sumRights(rights.toString().split(",")).toString();
        PageData pageData = new PageData();
        pageData.put("id",id);
        List<SystemRole> allOrOne = systemRoleService.findAll(pageData);
        if(null!=allOrOne||0!=allOrOne.size()){
            allOrOne.get(0).setBtnRights(newRights);
            systemRoleService.saveAll(allOrOne);
        }
        return "";
    }

    /**
     * 初始化权限
     * @param rights
     * @return
     */
    @RequestMapping(value = "/initMenu/{rights}" , produces = "application/json;charset=UTF-8")
    public Map<String,List<PageData>> initMenu(@PathVariable("rights") String rights){
        Map<String,List<PageData>> map = new HashMap<String, List<PageData>>();
        SystemMenu systemMenu = new SystemMenu();
        systemMenu.setId(0);
        systemMenu.setParentId("0");
        List<SystemMenu> allMenu = systemMenuService.findAll();
        List<PageData> result = new ArrayList<PageData>();
        result = new TreeMenuUtil().getTreeMenu(allMenu,systemMenuService);
        List<PageData> nodes = new ArrayList<PageData>();
        for(PageData tPageData : result ){
            if(tPageData.getString("PARENT_ID").equals("0")){
                int mu = Integer.valueOf(tPageData.get("MENU_ID").toString());
                PageData parentPD = new PageData();
                parentPD.put("id",mu);
                parentPD.put("pId",tPageData.getString("PARENT_ID"));
                parentPD.put("name",tPageData.getString("MENU_NAME"));
                parentPD.put("checked", RightsHelper.testRights(rights.substring(1),mu));
                nodes.add(parentPD);
                List<SystemMenu> firstSubMenu = (List<SystemMenu>) tPageData.get("firstSubMenu");
                for(SystemMenu subPageData : firstSubMenu){
                    int smu = subPageData.getId();
                    PageData firstPD = new PageData();
                    firstPD.put("id",smu);
                    firstPD.put("pId",subPageData.getParentId());
                    firstPD.put("name",subPageData.getMenuName());
                    firstPD.put("checked", RightsHelper.testRights(rights.substring(1),smu));
                    nodes.add(firstPD);
                }
            }
        }
        map.put("nodes",nodes);
        return map;
    }



    @RequestMapping("/role-ins-upd-del/{flag}")
    public String roleInsUpdDel(@PathVariable("flag") String flag){
        PageData pageData = this.getPageData();

        if(InsUpdDelFlagConstant.DELETE.equals(flag)){
            systemRoleService.deleteById(Integer.valueOf(pageData.get("role_id").toString()));
            return "";
        }

        SystemRole systemRole = new SystemRole();
        if(pageData.get("role_id")!=null){
            systemRole.setId(Integer.valueOf(pageData.get("role_id").toString()));
        }
        systemRole.setRoleName(pageData.getString("role_name"));
        systemRole.setRights(pageData.getString("rights")==null?"R0":pageData.getString("rights"));
        systemRole.setBtnRights(pageData.getString("btnRights")==null?"B0":pageData.getString("btnRights"));
        systemRoleService.save(systemRole);
        return "";
    }


    @RequestMapping("/role-list")
    public Object adminGetRoleList(){
        List<PageData> pageDataList = new ArrayList<PageData>();
        List<SystemRole> roleEntities = systemRoleService.findAll();
        for(SystemRole roleEntity : roleEntities){
            PageData pd = new PageData();
            pd.put("value",roleEntity.getId());
            pd.put("text",roleEntity.getRoleName());
            pageDataList.add(pd);
        }
        return JSONArray.toJSONString(pageDataList);
    }

    @RequestMapping("/role-id2name/{roleId}")
    public String adiminRoleId2RoleName(@PathVariable("roleId") Integer roleId){
        PageData pageData = new PageData();
        pageData.put("id", roleId);
        List<SystemRole> roleEntities = systemRoleService.findAll(pageData);
        if(1==roleEntities.size()){
            return roleEntities.get(0).getRoleName();
        }
        return "";
    }
}
